use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;

fn main() {
    let args: Vec<String> = env::args().collect();
    // 命令行参数 ["./rust-learning", "a", "bc", "dd"]
    // 接收文件路径
    for i in 1..args.len() {
        let arg = args.get(i).unwrap();
        let path = Path::new(arg);
        let display = path.display();

        let file = match File::open(path) {
            Err(why) => panic!("could not open {}: {}", display, why.description()),
            Ok(file) => file,
        };
        let new_file = format!("{}.bak", arg);
        let target = File::create(new_file).unwrap();
        let mut writer = BufWriter::new(target);

        let reader = BufReader::new(file);

        // 读取文件中的行
        for line in reader.lines() {
            // 读取文件行元素中的字符
            let line = line.unwrap();

            let pos = match line.bytes().position(|b| !b.is_ascii_digit()) {
                Some(pos) => pos,
                None => line.len(),
            };

            // 字符串切片
            writer.write_all( &line.as_bytes()[pos..]).unwrap();
            writer.write_all(b"\n").unwrap()
        }
        writer.flush().unwrap();
    }
}
